// 通常可以吧 baseUrl 单独放在一个 js 文件了
import config from "@/config/index";
let { baseUrl, ports } = config
import utils from "@/utils/utils.js";

const request = (options = {}) => {
  // 在这里可以对请求头进行一些设置
  options.header = {
    "content-type": "application/json",
  }

  //判断端口
  let port = 18089
  for (let index = 0; index < ports.length; index++) {
    const element = ports[index];
    let url = utils.substringFn(options.url)
    if (url == element) {
      port = 18087
    }
  }
  if (options.url.includes("/api")) {
    port = 18082
  }

  let slParams = uni.getStorageSync("slParams")
  if (slParams && slParams.token) { //本地环境
    options.header['Authorization'] = slParams.token
    //options.header['Authorization'] = "eyJhbGciOiJIUzI1NiJ9.eyJtb2JpbGUiOiIxNzgzNTUwMDEwNCIsImlkIjoxfQ.Vax2afehrlnRAS5vpf5oOmp1yTyeADaY8mO-yLcd2i0"
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}:${port}` + options.url || '',
      method: (options.type ? options.type : options.method.toLocaleUpperCase()) || 'GET',
      data: options.data || {},
      header: options.header || {}
    }).then(data => {
      if (data.data.code == 200) {
        resolve(data.data.data);
      } else if (data.data.code == 401) { //登录过期
        uni.clearStorageSync("slParams");//同步清理缓存
        utils.showToast(data.data.msg)
        reject(data.data.msg)
        //utils.toLink("/packagePages/login/startUpPage")
      }
      else {
        let msg = data.data.message || data.data.msg || '请求失败'
        utils.showToast(msg)
        reject(msg)
      }
    }).catch(error => {
      console.log("error", error)
      reject(error)
    })
  });
}

const get = (url, data, options = {}) => {
  options.type = 'GET';
  options.data = data;
  options.url = url;
  return request(options)
}

const post = (url, data, options = {}) => {
  options.type = 'POST';
  options.data = data;
  options.url = url;
  return request(options)
}


export default {
  request,
  get,
  post
}
